package com.micro.ai.gateway.filter;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Timer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 监控过滤器
 * 记录关键指标：QPS、响应时间、错误率等
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@Component
public class MonitorFilter implements GlobalFilter, Ordered {

    @Autowired
    private Counter requestCounter;

    @Autowired
    private Counter errorCounter;

    @Autowired
    private Timer responseTimer;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        long startTime = System.currentTimeMillis();
        
        // 记录请求计数
        requestCounter.increment();
        
        return chain.filter(exchange)
                .doOnSuccess(aVoid -> {
                    // 记录成功请求的响应时间
                    long duration = System.currentTimeMillis() - startTime;
                    responseTimer.record(duration, java.util.concurrent.TimeUnit.MILLISECONDS);
                    
                    log.debug("请求处理成功 - URI: {}, Duration: {}ms", 
                        request.getURI(), duration);
                })
                .doOnError(throwable -> {
                    // 记录错误计数
                    errorCounter.increment();
                    
                    log.error("请求处理失败 - URI: {}, Error: {}", 
                        request.getURI(), throwable.getMessage());
                });
    }

    @Override
    public int getOrder() {
        return 900; // 监控过滤器优先级
    }
}
